<?php

namespace app\api\controller;

use think\Db;
use app\admin\model\Train;
use app\admin\model\Dynamic;
use app\admin\model\Subject;
use app\common\controller\Api;

/**
 * 行政部
 */
class Xingzheng extends Api
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['index','analysis','getAnalysisList'];

    /**
     * 行政数据统计
     *
     */
    public function analysis()
    {
        $type = $this->request->param('type/d', 1); // 1月,2季度,3年
        $year = $this->request->param('year/s', date('Y'));
        $season = $this->request->param('season/s'); // 季度
        $month = $this->request->param('month/s', date('m')); // 月份
        switch ($type) {
                // +0为了返回为数据类型
            case '1':
                [$start, $end] = getMonthStartToEnd($year, $month);
                $format = "FROM_UNIXTIME(createtime,'%u')+0 as date";
                $range = array_range(date('W', $start), date('W', $end));
                $range_str = array_map(function ($item) {
                    return "第{$item}周";
                }, $range);
                break;
            case '2':
                [$start, $end] = getQuarter($year, $season);
                $format = "FROM_UNIXTIME(createtime,'%m')+0 as date";
                $quarter_month = [
                    1 => [1, 2, 3],
                    2 => [4, 5, 6],
                    3 => [7, 8, 9],
                    4 => [10, 11, 12],
                ];
                $range = $quarter_month[$season] ?? [1, 2, 3];
                $range_str = array_map(function ($item) {
                    return "{$item}月";
                }, $range);
                break;
            case '3':
                [$start, $end] = getYearStartToEnd($year);
                $format = "quarter(FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s'))+0 as date";
                $range = [1, 2, 3, 4];
                $range_str = array_map(function ($item) {
                    return "第{$item}季度";
                }, $range);
                break;
            default:
                return $this->error('参数错误！');
                break;
        }

        $data = [];
        foreach (['dynamic', 'subject', 'train'] as $tablename) {
            $temp_data = Db::name($tablename)->field([
                $format,
                'count(*) as total'
            ])
                ->whereTime('createtime', 'between', [$start, $end])
                ->group('date')
                ->select();
            $data[$tablename] = arraySort(getDataInTimeSpan($temp_data, $range), 'date', SORT_ASC);
        }
        $column = [
            'categories' => $range_str,
            'series' => [
                [
                    'name' => '动态发布数量',
                    'data' => array_column($data['dynamic'], 'total'),
                ],
                [
                    'name' => '题库更新数量',
                    'data' => array_column($data['subject'], 'total'),
                ],
                [
                    'name' => '培训资料更新数量',
                    'data' => array_column($data['train'], 'total'),
                ],
            ]
        ];
        return $this->success('ok', compact('column'));
    }

    /**
     * 统计列表（根据天统计）
     */
    public function getAnalysisList()
    {
        $page = $this->request->param('page/d', 1);
        $limit = $this->limit;
        [$start_time, $end_time] = getTiamStartToEnd($page, $limit);
        $range = getDayRange($start_time, $limit);
        $data = [];
        foreach (['dynamic', 'subject', 'train'] as $table) {
            $tmp = Db::name($table)->field([
                'count(*)' => 'total',
                "FROM_UNIXTIME(createtime,'%Y-%m-%d')" => 'date'
            ])
                ->group('date')
                ->whereTime('createtime', 'between', [$start_time, $end_time])
                ->select();
            $data[$table] = arraySort(getDataInTimeSpan($tmp, $range), 'date', SORT_DESC);
        }

        $list = array_map(function ($dynamic, $subject, $train) {
            return [
                'date' => $dynamic['date'],
                'dynamic_total' => $dynamic['total'],
                'subject_total' => $subject['total'],
                'train_total' => $train['total'],
            ];
        }, $data['dynamic'], $data['subject'], $data['train']);

        return $this->success('ok', compact('list'));
    }
}
